04 / 04

How do you build a minimal Docker image for a Go service?

Use a multi-stage Docker build: compile in a golang image, then copy only the binary to a distroless or scratch image. Result is a 5-15MB image vs 800MB+ with the full Go image.

Production multi-stage Dockerfile
Image size optimization
  1. 1

    distroless/static: ~3MB base, includes CA certs and timezone data — recommended for most services

  2. 2

    scratch: 0 bytes base — only works if your binary is 100% static and you don't need CA certs

  3. 3

    -ldflags '-w -s' strips debug info — reduces binary size by 20-30%

  4. 4

    Cache go mod download layer separately — rebuilds only when go.mod/go.sum change

  5. 5

    Run as non-root user in production — distroless nonroot image provides uid 65532